package server;

import java.io.IOException;
import java.net.DatagramPacket;

public class MessageReceiver implements Runnable{
	private Thread t;
	Object runOb=new Object();
	MessageReceiver(){
		t=new Thread(this);
		t.start();
	}
	public void run() {
		while(true){
			byte[] data=new byte[1024];
			DatagramPacket dp=new DatagramPacket(data,data.length);
			try {
				Config.ds.receive(dp);
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
			Config.messageQueue.add(dp);
			synchronized (runOb){
				if(Config.run&Config.messageQueue.size()!=0){
					runOb.notify();
				}
			}
		}
	}
	
	DatagramPacket getPacket(){
		synchronized (runOb){
			if(Config.messageQueue.size()==0|!Config.run){
				try {
					runOb.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			DatagramPacket dp=Config.messageQueue.get(0);
			DatagramPacket dp2=null;
			if(dp!=null){
				dp2=new DatagramPacket(dp.getData(),dp.getLength());
				dp2.setAddress(dp.getAddress());
				dp2.setPort(dp.getPort());
			}
			
			Config.messageQueue.remove(0);
			return dp2;
		}
	}
	
	void pause(){
		Config.run=false;
	}
	
	void play(){
		synchronized (runOb){
			Config.run=true;
			if(Config.messageQueue.size()!=0){
				runOb.notify();
			}
		}
	}
}
